﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SampleSite.template
{
    public partial class _default : Page
    {
        public DynamicTable Table { get; set; }

        public UserInfo Login { get; set; }

        protected override void OnLoad(EventArgs e)
        {
            if (string.CompareOrdinal(
                this.Request.Path,
                "/template/default.aspx") == 0)
            {
                this.WriteParentRediret("~/default.aspx");
                this.Response.End();
                return;
            }

            this.Table = (DynamicTable)this.Context.Items["Table"];
            this.Login = (UserInfo)this.Context.Items["User"];

            base.OnLoad(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public string GetAttributes(DynamicColumn column)
        {
            StringBuilder builder = new StringBuilder();
            switch (column.TypeId)
            {
                case ColumnType.DATE:
                    builder.Append(",formatter:formatter_date");
                    break;

                case ColumnType.DATETIME:
                    builder.Append(",formatter:formatter_datetime");
                    break;

                case ColumnType.TIME:
                    builder.Append(",formatter:formatter_time");
                    break;
            }

            return builder.ToString();
        }

        public string GetInput(string id, DynamicColumn column)
        {
            var control = MetadataManager.GetControl(column.ControlId);
            StringBuilder builder = new StringBuilder();

            builder.Append(column.Required ? "required:true" : "required:false");
            if (column.TypeId == ColumnType.DECIMAL)
            {
                builder.Append(",precision:");
                builder.Append(column.Precision);
            }

            return string.Format(control.HtmlTemplate,
                id+column.Name,
                column.Name,
                builder.ToString());
        }

        public void WriteParentRediret(string url)
        {
            this.Response.Write(string.Format(
@"<script type=""text/javascript"">
    if(top != this)
        parent.location.href='{0}';
    else
        document.location.href = '{0}';
</script>",
                    this.ResolveUrl(url)));
        }
    }
}